from django.core.cache import cache
from django.contrib.auth.forms import UserCreationForm
from django.views.generic.simple import direct_to_template
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from machete.forms import CreateGreetingForm, AdminCreatePageForm
from machete.models import Greeting,Page,Category, Slideshow, Photo,\
                        LinkSlideshowPage, LinkPhotoSlideshow
from machete.detailviews import LinkSlideshowPageDetailView

MEMCACHE_GREETINGS = 'greetings'
MEMCACHE_PAGES = 'pages'

def list_greetings(request):
    greetings = cache.get(MEMCACHE_GREETINGS)
    if greetings is None:
        greetings = Greeting.objects.all().order_by('-date')[:10]
        cache.add(MEMCACHE_GREETINGS, greetings)
    return direct_to_template(request, 'machete/index.html',
                              {'greetings': greetings,
                               'form': CreateGreetingForm()})

def create_greeting(request):
    if request.method == 'POST':
        form = CreateGreetingForm(request.POST)
        if form.is_valid():
            greeting = form.save(commit=False)
            if request.user.is_authenticated():
                greeting.author = request.user
            greeting.save()
            cache.delete(MEMCACHE_GREETINGS)
    return HttpResponseRedirect('/machete/')

def create_new_user(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            # user must be active for login to work
            user.is_active = True
            user.save()
            return HttpResponseRedirect('/machete/')
    else:
        form = UserCreationForm()
    return direct_to_template(request, 'machete/user_create_form.html',
        {'form': form})
    

# ======= Page ======= #
def view_page(request,entity_id):
    entity = get_object_or_404(Page, pk=entity_id)
    return view_page_entity(request, entity)

def view_page_last(request):
    firstcategory = Category.objects.order_by('order')[0:1].get()
    firstpage = firstcategory.page_set.order_by('order')[0:1].get()
    return view_page_entity(request, firstpage)

def view_page_entity(request,entity):
    return direct_to_template(request, 'machete/page/view_page.html',
                              {'view_page': entity,
                               'slideshows': entity.slideshows(),
                               'menu_categories': Category.objects.all(),})
#                               'menu_pages': Page.objects.all(),})